//
//  SDFormBaseData.m
//  SKinDiary
//
//  Created by pcyang on 16/7/11.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDFormBaseData.h"
#import "SDHTTPRequestOperation.h"
#import "SDLoginManager.h"


@interface SDFormBaseData()
@property(nonatomic,strong) NSObject* responseModel;
@property(nonatomic,strong) SDHTTPRequestOperation*     request;
@end

@implementation SDFormBaseData
-(id) getFilePartInfoWithFileUrl:(NSURL*) fileUrl partName:(NSString*) partName fileName:(NSString*) fileName mimeType:(NSString*) mimeType
{
    SDFormPartInfo* partInfo = [[SDFormPartInfo alloc] init];
    
    partInfo.fileUrl = fileUrl;
    partInfo.partName = partName;
    partInfo.fileName = fileName;
    partInfo.mimeType = mimeType;
    
    return partInfo;
}


-(void)uploadFormDataWithUserInfo:(NSDictionary*) userInfo
{
    
    NSString* url = [self getFullURL];
    NSDictionary* values = [self getPostDictionary];
    
    NSMutableDictionary *totalParams = [NSMutableDictionary dictionaryWithCapacity:4];
    if (values && values.count > 0)
    {
        [totalParams addEntriesFromDictionary:values];
    }
    
    //公共参数
   // [totalParams addEntriesFromDictionary:[SDCommonFunction GetCommonParams]];
    
    if (nil==url || nil==totalParams)
    {
        NSError* err = [NSError errorWithDomain:SDHttpRequest_ErrorDomain code:SDHttpRequest_Errorcode_InParamError userInfo:nil];
        [self refreshDataDidFinishWithUserInfo:userInfo error:err];
        return;
    }
    
    if(_request)
        [_request clearDelegatesAndCancel];
    
    [self refreshDataWillStart];
    
    Class selfClass = self.class;
    __weak typeof(self) weakSelf = self;
    __weak NSDictionary *weakUserInfo = userInfo;
    
    
    self.request = [SDHttpRequestManagement startHttpPostRequestWithURL:url
                                                               postValue:totalParams
                                                          requestCookies:[self requestCookies]
                                                              jsonParser:YES
                                                                priority:SDHttpRequestPriority_VeryHigh
                                                       objectParserBlock:^id(id data, NSError *__autoreleasing *error)
                    {
                        id realData = [selfClass realJosnDataFromResponseData:data err:error];
                        return [selfClass modelFromResponseValues:realData error:error];
                    }
                                                              completion:^(id data, NSError *error)
                    {
                        __strong SDFormBaseData* strongSelf = weakSelf;
                        
                        if( !error )
                        {
                            strongSelf.responseModel = [strongSelf resetWithResponseModel:data];
                        }
            
                        
                        if(nil==error)
                        {
                        }
                        else
                        {
                            NSInteger code = error.code;
                            if(SDHttpRequest_Errorcode_ResponseError==error.code && error.userInfo)
                                code = [[error.userInfo objectForKey:kSDHttpRequest_ResponseCode] integerValue];
                            
                        }
                        
                        strongSelf.request = nil;
                        [strongSelf refreshDataDidFinishWithUserInfo:weakUserInfo error:error];
                    }];
}

+(id)realJosnDataFromResponseData:(id)data err:(NSError**)error
{
    id realData = nil;
    
    if( error && *error == nil )
    {
        BOOL success = NO;
        NSString* code = nil;
        
        if( [data isKindOfClass:[NSDictionary class]] )
        {
            code = [data objectForKey:@"code"];
            
            if(code && [code isKindOfClass:[NSNumber class]])
                code = [NSString stringWithFormat:@"%d", [code intValue]];
            
            if(code)
                success = (code ? [code intValue]==0:NO);
            
            if( success )
            {
                realData = [data objectForKey:@"data"];
            }
        }
        
        if( !success )
        {
            NSString* errInfo = [data objectForKey:@"msg"];
            
            *error = [NSError errorWithDomain:SDHttpRequest_ErrorDomain
                                         code:SDHttpRequest_Errorcode_ResponseError
                                     userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
                                               getShowString(errInfo),kSDHttpRequest_ResponseInfo,
                                               getShowString(code), kSDHttpRequest_ResponseCode,nil]];
        }
    }
    
    return realData;
}

#pragma mark ---

-(NSDictionary*)requestCookies
{
    SDLoginManager* loginMgr = [SDLoginManager sharedInstance];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:5];
    NSString* sessionId = [loginMgr sessionId];
    if (CHECK_VALID_STRING(sessionId)) {
        [dic setObject:[loginMgr sessionId] forKey:@"Token"];
    }
    
    // return [[SDUserService defaultUserService] getCookiesDic];
    return dic;
}

-(NSString*)getHTTPMethod
{
    return nil;
}

-(NSString*)getFullURL
{
    return nil;
}

-(NSDictionary*) getPostDictionary
{
    return nil;
}

+(id)modelFromResponseValues:(id)infos error:(NSError**)error
{
    return infos;
}

-(id)resetWithResponseModel:(id)data
{
    return data;
}

#pragma mark ---
- (BOOL)isLoading
{
    return (nil!=_request);
}

- (void)clear
{
    if(_request)
    {
        [_request clearDelegatesAndCancel];
        _request = nil;
    }
}

- (void)clearDelegatesAndCancel
{
    [self clear];
    _delegate = nil;
}

- (void)refreshDataWillStart
{
    if( self.delegate && [self.delegate respondsToSelector:@selector(willUploadOfFormData:)] )
        [self.delegate willUploadOfFormData:self];
}

- (void)refreshDataDidFinishWithUserInfo:(NSDictionary*) userInfo error:(NSError*)error
{
    if( self.delegate && [self.delegate respondsToSelector:@selector(formData:userInfo:didFinishLoadWithError:)] )
        [self.delegate formData:self userInfo:userInfo didFinishLoadWithError:error];
}


#pragma mark ---

-(void) dealloc
{
    [self clear];
}


-(void)excuteHttpRequest
{
    NSString* url = [self getFullURL];
    NSDictionary* values = [self getPostDictionary];
    
    NSMutableDictionary *totalParams = [NSMutableDictionary dictionaryWithCapacity:4];
    if (values && values.count > 0)
    {
        [totalParams addEntriesFromDictionary:values];
    }
    
    //公共参数
    // [totalParams addEntriesFromDictionary:[SDCommonFunction GetCommonParams]];
    
    if (nil==url || nil==totalParams)
    {
        NSError* err = [NSError errorWithDomain:SDHttpRequest_ErrorDomain code:SDHttpRequest_Errorcode_InParamError userInfo:nil];
        [self refreshDataDidFinishWithUserInfo:nil error:err];
        return;
    }
    
    if(_request)
        [_request clearDelegatesAndCancel];
    
    [self refreshDataWillStart];
    
    Class selfClass = self.class;
    __weak typeof(self) weakSelf = self;
    
    self.request = [SDHttpRequestManagement startRequestWithHttpMethod:[self getHTTPMethod] url:url postValue:totalParams requestCookies:[self requestCookies] jsonParser:YES priority:SDHttpRequestPriority_Normal objectParserBlock:^id(id data, NSError *__autoreleasing *error)
                    {
                        id realData = [selfClass realJosnDataFromResponseData:data err:error];
                        return [selfClass modelFromResponseValues:realData error:error];
                    } completionQueue:nil completion:^(id data, NSError *error) {
                        __strong SDFormBaseData* strongSelf = weakSelf;
                        
                        if( !error )
                        {
                            strongSelf.responseModel = [strongSelf resetWithResponseModel:data];
                        }
                        
                        
                        if(nil==error)
                        {
                        }
                        else
                        {
                            NSInteger code = error.code;
                            if(SDHttpRequest_Errorcode_ResponseError==error.code && error.userInfo)
                                code = [[error.userInfo objectForKey:kSDHttpRequest_ResponseCode] integerValue];
                            
                        }
                        
                        strongSelf.request = nil;
                        [strongSelf refreshDataDidFinishWithUserInfo:nil error:error];
        
    }];
    
}

@end
